package baidu

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"sync"
	"wxgf/library/easyHttp"
)

var (
	accessToken string
	expires     int64
	mu          sync.Mutex
)

const baiduAuthPath = "https://aip.baidubce.com/oauth/2.0/token"

func getToken() (string, error) {
	if gtime.Now().Timestamp() >= expires {
		mu.Lock()
		if gtime.Now().Timestamp() >= expires {
			err := requestBaiduAuth()
			if err != nil {
				return "", err
			}
		}
		mu.Unlock()
	}

	return accessToken, nil
}

func requestBaiduAuth() error {
	_, body, err := easyHttp.Ctx().Post(baiduAuthPath, g.Map{
		"grant_type":    "client_credentials",
		"client_id":     Client.apiKey,
		"client_secret": Client.apiSecret,
	})
	if err != nil {
		return fmt.Errorf("%s, body=%s", err.Error(), body)
	}

	var res struct {
		Error            string `json:"error"`
		ErrorDescription string `json:"error_description"`
		ExpiresIn        int64  `json:"expires_in"`
		AccessToken      string `json:"access_token"`
	}

	gconv.Struct(body, &res)
	if res.Error != "" {
		return fmt.Errorf("%s, body=%s", res.Error, body)
	}

	accessToken = res.AccessToken
	expires = gtime.Now().Timestamp() + expires - 86400*7 // 提前7天过期
	return nil
}
